package com.ahuan.controller;

import com.ahuan.domain.Menu;
import com.ahuan.domain.User;
import com.ahuan.exception.BusinessException;
import com.ahuan.mapper.LoginMapper;
import com.ahuan.resp.LoginRes;
import com.ahuan.resp.Res;
import com.ahuan.service.LoginService;
import com.ahuan.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    LoginService loginService;

    @PostMapping("/login")
    public LoginRes user(String username, String password, String code, HttpServletRequest request) {
        try {
            log.info("username:{},code:{}", username, code);

            // 验证码校验
            HttpSession session = request.getSession();
            String codeReal = (String) session.getAttribute("codeReal");
            if (!code.equalsIgnoreCase(codeReal)) {
                log.info("Login Fail,Error Code：{}", codeReal);
                return LoginRes.codeError();
            }
            session.removeAttribute("codeReal");

            // 用户名和密码检验
            User user = loginService.login(username, password);
            if (user != null) {// 查询到用户信息
                log.info("login success");
                Date date = new Date(System.currentTimeMillis());
                String token = JwtUtil.sign(user.getUserId()
                        , user.getUserName()
                        , date.toString());
                session.setAttribute("token", token);// todo 暂时将token放在session中，实际应用中需要放在redis等地方
                return LoginRes.loginSuccess(null, token);
            }
            return LoginRes.loginFail();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("登录失败");
        }
    }



    @GetMapping("/menu")
    public Res menu() {
        try {
            String userId = MDC.get("userId");
            String userName = MDC.get("userName");
            log.info("{}用户请求菜单",userName);

            List<Menu> list = loginService.queryMenu(userId);
            if(CollectionUtils.isEmpty(list)){
                return Res.failOperate();
            }
            return  Res.successOperate(list);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new BusinessException("登录时查询用户权限菜单失败");
        }
    }

}
